<template>
    <el-form :model="loginUser" :rules="rules" ref="loginForm" label-width="100px" class="loginForm sign-in-form">
        <el-form-item label="邮箱" prop="email">
            <el-input v-model="loginUser.email" placeholder="Enter Email..."></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input v-model="loginUser.password" type="password" placeholder="Enter Password..."></el-input>
        </el-form-item>
        <el-form-item>
            <el-button @click="handleLogin" type="primary" class="submit-btn">提交</el-button>
        </el-form-item>

        <!-- 找回密码 -->
        <div class="tiparea">
            <p>忘记密码？ <a>立即找回</a></p>
        </div>
    </el-form>
</template>

<script lang="ts">
  import { getCurrentInstance } from "vue";
  import { useRouter } from "vue-router";

  export default {
    name: "loginForm",
    props: {
      loginUser: {
        type: Object,
        require: true
      },
      rules: {
        type: Object,
        require: true
      }
    },
    setup(props: any){
      // @ts-ignore
      const { ctx } = getCurrentInstance();  // getCurrentInstance获取当前组件的实例,ctx属性获取上下文
      const router = useRouter();
      const url = "/api/v1/auth/login";

      const handleLogin = () => {
        ctx.$refs.loginForm.validate((val: boolean) => {
          console.log(val)
          if (!val) return;
          ctx.$axios.post(url, props.loginUser).then((res: any) => {
            if (res.success) {
              ctx.$message.success("登录成功")
              router.push("/")

              // 缓存token
              localStorage.setItem("token", res.token)
            } else {
              ctx.$message.error("登录失败")
            }

          }).catch(() => {
            ctx.$message.error("登录失败")
          })
        })
      }

      return { handleLogin }
    }
  }
</script>

<style scoped>
    .loginForm {
        margin-top: 20px;
        background-color: #fff;
        padding: 20px 40px 20px 20px;
        border-radius: 5px;
        box-shadow: 0px 5px 10px #cccc;
    }
    .tiparea {
        text-align: right;
        font-size: 12px;
        color: #333;
    }
    .tiparea p a {
        color: #409eff;
    }
    /* 控制login & register显示 */
    form {
        padding: 0rem 5rem;
        transition: all 0.2s 0.7s;
        overflow: hidden;
    }

    form.sign-in-form {
        z-index: 2;
    }

    form.sign-up-form {
        opacity: 0;
        z-index: 1;
    }

    .submit-btn {
        width: 100%;
    }
</style>